﻿using Dto;
using IBLL;
using IDAL;
using Model;

namespace BLL
{
    public class EmployeeBLL : IEmployeeBLL
    {
        public EmployeeBLL(IEmployeeDAL<EmployeeModel> dal,IEmployeeDAL<TypeModel> tdal)
        {
            Dal = dal;
            Tdal = tdal;
        }

        public IEmployeeDAL<EmployeeModel> Dal { get; }
        public IEmployeeDAL<TypeModel> Tdal { get; }

        public Task<int> AddEmployee(EmployeeModel employee)
        {
            return Dal.AddAsync(employee);
        }

        public Task<int> DeleteRangeEmployee(string idstring)
        {
            List<int>ints=idstring.Split(',').Select(a=>Convert.ToInt32(a)).ToList();
            var emplist = Dal.GetAllAsync().Where(a => ints.Contains(a.Id));
            foreach (var item in emplist)
            {
                item.IsDelete = true;
                item.DeleteTime = DateTime.Now;
            }
            return Dal.UpdaRangeAsync(emplist.ToList());


        }

        public EmployeeShowDto EmployeeShow(string? name, int typeid, int pageindex, int pagesize)
        {
            var a = Dal.GetAllAsync().Where(a=>a.IsDelete==false);
            var b= Tdal.GetAllAsync();
            var sql = from c in a
                      join d in b on c.tid equals d.Tid
                      select new 
                      {
                          c.Id,
                          c.EmployeeName,
                          c.Sex,
                          c.Img,
                          c.tid,
                          c.Room,
                          c.Peoples,
                          c.Jg,
                          c.IdCard,
                          c.Phone,
                          c.State,
                          d.TypeName
                      };
            if (!string.IsNullOrEmpty(name)) 
            {
                sql = sql.Where(a => a.EmployeeName.Contains(name));
            }
            if (typeid > 0) 
            {
                sql = sql.Where(a => a.tid == typeid);
            }
            var s = sql.Count();
            var m = sql.OrderBy(a => a.Id).Skip((pageindex - 1) * pagesize).Take(pagesize);
            return new EmployeeShowDto { Count=s,Members=m };
        }

        public EmployeeModel Fan(int id)
        {
            return Dal.GetAllAsync().FirstOrDefault(a => a.Id == id);
        }

        public Task<int> UpdateEmployee(EmployeeModel employee)
        {
            return Dal.UpdateAsync(employee);
        }

        public Task<int> UpdateRangeUpdate(string idstring)
        {
            List<int> ints = idstring.Split(',').Select(a => Convert.ToInt32(a)).ToList();
            var emplist = Dal.GetAllAsync().Where(a => ints.Contains(a.Id));
            foreach (var item in emplist)
            {
                item.State = item.State == 1 ? 2 : 1;
                item.UpdateTime = DateTime.Now;
            }
            return Dal.UpdaRangeAsync(emplist.ToList());
        }
    }
}
